#!/usr/bin/ruby

#意想股市类
class FtStockMarket
  attr_reader :stocks

  def initialize(pack_of_poker=2,stocks_count=4)
    #股票的个数
    @stocks_count=stocks_count
    @pokers = Pokers.new(pack_of_poker)
    @stocks = @pokers.average_alloc(stocks_count).map {|x| FtStock.new(x)}
  rescue => e
    err(e)
  end
  
  def set_1st_stock(cards)
	@stocks = [cards,[],[],[]]
  end
  
  def set_all_stock_same(stock_to_dup)
	@stocks = Array.new(4) {|stock| stock = stock_to_dup.dup}
  end

	def counts
		@stocks.map {|stock|stock.count}
	end

   #显示每股概况
  def str_stocks
	str = "| ";@stocks.each_with_index {|s,i| str << "stk#{i+1} : #{s.count} | "};str
  end
end

#意想股票类
class FtStock
	prepend ThreadIO

	#attr_reader :cards
	attr_accessor :cards
	
	def initialize(cards)
		@cards = cards
		@lock = Mutex.new
	end
	
	#创建cards的深拷贝
	def initialize_copy(other)
		@cards = other.cards.dup
	end

	#将一张翻开的牌重新翻回去
	def unturn(card)
		@lock.synchronize {
			@cards.unshift(card)
		}
	end

	#翻开一张牌
	def turn
		raise "该股已经开完" if @cards.size == 0
		@lock.synchronize {
			@cards.shift
		}
	end
	
	def pick_card(msg)
		card = turn
		#printf "#{msg}\t";sleep(1);printf "card is #{Pokers.color_str(card)}";puts ""
		printf "#{msg}\t";sleep(1);printf "card is #{Pokers.color_str(card)}\n"

		card
	end

	def count
		@lock.synchronize {
			@cards.count
		}
	end
end
